package com.ruoyi.system.controller.appcontroller;

import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.system.domain.ApUser;
import com.ruoyi.system.service.ApUserService;
import com.ruoyi.system.service.UserService;
import com.ruoyi.system.service.WechatLoginService;
import com.ruoyi.system.util.ResponseResult;
import com.ruoyi.system.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
//@RequestMapping("/system")
public class LoginController extends BaseController {
    @Autowired
    private ApUserService apUserService;
    @Autowired
    private WechatLoginService wechatLoginService;
    @Autowired
    private UserService userService;
    @PostMapping("/api/user/sendcode")
    public ResponseResult sendCode(@RequestBody Map<String, Object> map) {
        System.err.println("发送验证码:" + map);
        try {
            return apUserService.sendCode(map);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(400, "发送失败!" + e.getMessage());
        }
    }

    /**
     * app用户登录
     *
     * @param map
     * @return
     */
    @PostMapping("/api/user/login")
    public ResponseResult login(@RequestBody Map<String, Object> map) {
        System.err.println("登录:" + map);
        try {
            return apUserService.login(map);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(400, "登录失败!" + e.getMessage());
        }
    }

    /**
     * @param request
     * @return
     */
    @PostMapping("/api/userInfo/login")
    public Result Wxlogin(@RequestBody Map<String, String> request) {
        logger.info("收到微信登录请求，参数: {}", request);

        try {
            String code = request.get("code");
            if (code == null || code.isEmpty()) {
                logger.error("登录失败：code为空");
                return Result.error(400, "code不能为空");
            }

            // 1. 获取微信会话信息
            Map<String, Object> sessionInfo = wechatLoginService.getSessionInfo(code);
            logger.info("获取微信会话信息: {}", sessionInfo);

            if (sessionInfo.containsKey("errcode")) {
                String errmsg = (String) sessionInfo.get("errmsg");
                logger.error("微信登录失败，错误码: {}, 错误信息: {}",
                        sessionInfo.get("errcode"), errmsg);
                return Result.error(400, "微信登录失败：" + errmsg);
            }

            // 2. 获取openid
            String openid = (String) sessionInfo.get("openid");
            logger.info("获取openid成功: {}", openid);

            // 3. 处理用户登录
            Map<String, Object> userInfo = userService.handleUserLogin(openid);
            logger.info("用户登录成功，用户信息: {}", userInfo);

// 4. 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("token", userInfo.get("token"));
            result.put("user", userInfo.get("user"));
            result.put("openid", openid);
            return Result.success(200, result);
        } catch (Exception e) {
            logger.error("微信登录失败", e);
            return Result.error(400, "登录失败：" + e.getMessage());
        }
    }

    @PostMapping("/api/user/register")
    public Result register(@RequestBody ApUser user) {
        System.out.println("--------------");
        System.out.println(user);
        try {
            return apUserService.register(user);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(400, "注册失败!" + e.getMessage());
        }
    }
}
